#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <cstring>
#include <fstream>

using namespace std;

#define BUFFER_SIZE 1024
void munch2(int inpipe);
void write_file(int inpipe);

void munch1(int inpipe) {
	char read_msg[BUFFER_SIZE];
	int i = 0;

	pid_t pid;
	int fd[2];
	if(pipe(fd) == -1)
	{
		perror("Pipe error");
		return;
	}

	pid = fork();
	if(pid < 0)
	{
		perror("Fork Failed");
		return;
	}
	else if(pid == 0)
	{
		close(fd[1]);
        munch2(fd[0]);
		close(fd[0]);
		return;
	}
	else
	{
		read(inpipe, read_msg, BUFFER_SIZE);
		while(i++ <= BUFFER_SIZE)
		{
			if(read_msg[i] == ' ')
				read_msg[i] = '*';
		}
		printf("In Munch1, the msg is: %s\n", read_msg);
		close(fd[0]);
		write(fd[1], read_msg, (unsigned long)(strlen(read_msg)+1));
		close(fd[1]);
	}

	return;
}

void munch2(int inpipe) {
	char read_msg[BUFFER_SIZE];
	int i = 0;

	pid_t pid;
	int fd[2];
		if(pipe(fd) == -1)
	{
		perror("Pipe error");
		return;
	}

	pid = fork();
	if(pid < 0)
	{
		perror("Fork Failed");
		return;
	}
	else if(pid == 0)
	{
		close(fd[1]);
    write_file(fd[0]);
		close(fd[0]);
		return;
	}
	else
	{
		read(inpipe, read_msg, BUFFER_SIZE);
		while(i <= BUFFER_SIZE)
		{
			read_msg[i] = toupper(read_msg[i]);
			i++;
		}
		printf("In Munch2, the msg is: %s\n", read_msg);
		close(fd[0]);
		write(fd[1], read_msg, (unsigned long)(strlen(read_msg)+1));
		close(fd[1]);
	}

	return;
}

void write_file(int inpipe) {
	ofstream output_stream;
	char read_msg[BUFFER_SIZE];
	int i = 0;

	read(inpipe, read_msg, BUFFER_SIZE);
	printf("Before writing to the file, the msg is: %s\n", read_msg);

	output_stream.open("test_input_munched.dat", std::ios_base::app);
	output_stream << read_msg;
	output_stream << '\n';
	output_stream.close();

	return;
}

int main(int argc, char **argv)
{
	ifstream input_stream;
	string line;
	char write_msg[BUFFER_SIZE];

	input_stream.open("test_input.dat");

	while(!input_stream.eof()) {
		getline(input_stream, line);	
		// input_stream.close();
		strcpy(write_msg, line.c_str());
		printf("Starting the main(). \n");
		printf("In Reader, the msg is: %s\n", write_msg);
	    
		pid_t pid;
		int fd[2];

		if(pipe(fd) == -1)
		{
			perror("Pipe error");
			return(1);
		}

		pid = fork();
		if(pid < 0)
		{
			perror("Fork Failed");
			return(1);
		}
		else if(pid == 0)
		{
			close(fd[1]);
			munch1(fd[0]);
			close(fd[0]);
	        return 1;
		}
		else
		{
			close(fd[0]);
			write(fd[1], write_msg, strlen(write_msg)+1);
			close(fd[1]);
		}
	}
	input_stream.close();
	
	return(EXIT_SUCCESS);
}

